from django.shortcuts import render
import re

from django.contrib.auth import login
from django.http import HttpResponseBadRequest,HttpResponse
from django import http
from django.shortcuts import render, redirect
from django_redis import get_redis_connection

from django.views import View
from qingmei_mall.utils.response_code import  RETCODE
from qingmei_mall.utils import secret_openid as sect
from QQLoginTool.QQtool import OAuthQQ
from users.models import User
from .models import OauthMobile
from django.conf import settings  #qq导用setting配置dev

# Create your views here.
class QQ_OView(View):

    def get(self,request):
        #验证
        #响应

        #接受
        next_url=request.GET.get('next','/')
        # response=redirect(next_url)

        # 处理
        #生成appid appkey 回调地址next——url

        oathqq=OAuthQQ(settings.QQ_CLIENT_ID,settings.QQ_CLIENT_SECRET,settings.QQ_REDIRECT_URI)

        #get_qq_url调用创建授权地址
        login_urlqq=oathqq.get_qq_url()

        return http.JsonResponse({'code':RETCODE.OK,'errmsg':'ok','login_url':login_urlqq})

#获取openid
class QQ_open(View):
    def get(self,request):
        # 获取code

        state_url=request.GET.get('state','/')
        code=request.GET.get('code')
        #验证
        if not code :
            return http.HttpResponseBadRequest('code值为空')


        #发送获取token的请求
        oathqq=OAuthQQ(settings.QQ_CLIENT_ID,settings.QQ_CLIENT_SECRET,settings.QQ_REDIRECT_URI)

        token=oathqq.get_access_token(code)
        #发送获取openid的请求

        openid=oathqq.get_open_id(token)

        try:
            qq_user=OauthMobile.objects.get(openid=openid)
        except:

            secret_openid=sect.dump_(openid,60*5)
            render(request,'oauth_callback.html',{'token':secret_openid})

        else:
            login(request,qq_user.user)
            reponese=redirect(state_url)
            reponese.set_cookie('username',qq_user.user,60*60*24*14)
            return reponese

        return http.HttpResponse(openid)

        #使用openid_user新建表

    def post(self,request):

        mobile = request.POST.get('mobile')
        pwd = request.POST.get('pwd')
        openid = request.POST.get('access_token')
        sms_code_client=request.POST.get('sms_code')
        image_code = request.GET.get('image_code')



        #非空
        if not all([mobile, pwd,sms_code_client]):
            return HttpResponseBadRequest('缺少参数请填写')
        #手机号
        if not (re.match('^1[345789]\d{9}$', mobile)):
            return HttpResponseBadRequest("手机号输入错误")
        # 密码验证
        if not (re.match('^[0-9A-Za-z]{8,20}$', pwd)):
            return HttpResponseBadRequest('密码格试错误')

        #短信
        GetRedis_image = get_redis_connection('imagecode')
        image_code_redis = GetRedis_image.get('sms_'+mobile)  # 取值



        if image_code_redis.decode() != sms_code_client:
            # return http.JsonResponse({'code':RETCODE.IMAGECODEERR,'errmsg':'图形验证码不正确'})
            return render(request,'oauth_callback.html',{'sms_code_errmsg':'短信验证码不正确'})
        if image_code_redis is None:
            # return http.JsonResponse({'code':RETCODE.IMAGECODEERR,'errmsg':'图形验证码为空'})
            return render(request,'oauth_callback.html',{'sms_code_errmsg':'短信验证码为空'})

        if not sect.load_(openid):
            return  http.HttpResponseBadRequest('openid过期')

        try:
            #验证用户存在
            qq_user=User.objects.get(mobile=mobile)
        except:
            #用户不存在添加用户
            qq_user=User.objects.create_user(username=mobile,password=pwd,mobile=mobile)

        else:
            #验证密码#如果密码错误
            if not qq_user.check_password(pwd):
                return render(request,'oauth_callback.html',{'account_errmsg':'用户名或密码错误'})
        #如果密码正确  #绑定
        OauthMobile.objects.create(openid=openid,user=qq_user)
        #状态保持
        login(request,qq_user)
        response=redirect('state','/')
        response.set_cookie('username',qq_user.username,60*60*24*7)
        return response
